package org.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.app.common.Result;
import org.app.entity.Notice;
import org.app.service.NoticeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/notice")
public class NoticeController {
    
    private static final Logger log = LoggerFactory.getLogger(NoticeController.class);
    
    @Autowired
    private NoticeService noticeService;
    
    /**
     * 分页查询公告列表
     */
    @GetMapping("/page")
    public Result<Page<Notice>> getPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword) {
        LambdaQueryWrapper<Notice> wrapper = new LambdaQueryWrapper<>();
        
        // 只查询显示状态的公告
        wrapper.eq(Notice::getStatus, 1);
        
        // 模糊查询
        if (StringUtils.hasText(keyword)) {
            wrapper.like(Notice::getTitle, keyword)
                    .or()
                    .like(Notice::getContent, keyword);
        }
        
        // 优先显示置顶公告，再按创建时间排序
        wrapper.orderByDesc(Notice::getIsTop)
                .orderByDesc(Notice::getCreateTime);
        
        // 分页查询
        Page<Notice> page = new Page<>(pageNum, pageSize);
        noticeService.page(page, wrapper);
        
        return Result.success(page);
    }
    
    /**
     * 管理员分页查询公告列表
     */
    @GetMapping("/admin/page")
    public Result<Page<Notice>> getAdminPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status) {
        log.info("管理员查询公告列表参数: pageNum={}, pageSize={}, keyword={}, status={}", 
                pageNum, pageSize, keyword, status);
        
        LambdaQueryWrapper<Notice> wrapper = new LambdaQueryWrapper<>();
        
        // 按状态筛选，status为null时不筛选
        if (status != null) {
            log.info("应用状态筛选: status={}", status);
            wrapper.eq(Notice::getStatus, status);
        }
        
        // 模糊查询
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like(Notice::getTitle, keyword)
                    .or()
                    .like(Notice::getContent, keyword));
        }
        
        // 按创建时间排序
        wrapper.orderByDesc(Notice::getCreateTime);
        
        // 分页查询
        Page<Notice> page = new Page<>(pageNum, pageSize);
        noticeService.page(page, wrapper);
        
        log.info("查询结果: 总记录数={}", page.getTotal());
        return Result.success(page);
    }
    
    /**
     * 根据ID查询公告详情
     */
    @GetMapping("/{id}")
    public Result<Notice> getById(@PathVariable Long id) {
        Notice notice = noticeService.getById(id);
        return Result.success(notice);
    }
    
    /**
     * 添加公告
     */
    @PostMapping
    public Result<Void> add(@RequestBody Notice notice, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        notice.setAuthorId(userId);
        noticeService.save(notice);
        return Result.success();
    }
    
    /**
     * 修改公告
     */
    @PutMapping
    public Result<Void> update(@RequestBody Notice notice) {
        // 如果只更新部分字段，先获取原公告信息
        if (notice.getTitle() == null || notice.getContent() == null) {
            Notice existingNotice = noticeService.getById(notice.getId());
            if (existingNotice == null) {
                return Result.error("公告不存在");
            }
            
            // 只更新提供的字段
            if (notice.getTitle() == null) {
                notice.setTitle(existingNotice.getTitle());
            }
            if (notice.getContent() == null) {
                notice.setContent(existingNotice.getContent());
            }
            if (notice.getStatus() == null) {
                notice.setStatus(existingNotice.getStatus());
            }
            if (notice.getIsTop() == null) {
                notice.setIsTop(existingNotice.getIsTop());
            }
            if (notice.getAuthorId() == null) {
                notice.setAuthorId(existingNotice.getAuthorId());
            }
        }
        
        noticeService.updateById(notice);
        return Result.success();
    }
    
    /**
     * 删除公告
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        noticeService.removeById(id);
        return Result.success();
    }
    
    /**
     * 更新公告状态
     */
    @PutMapping("/status/{id}")
    public Result<Void> updateStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {
        Notice notice = new Notice();
        notice.setId(id);
        notice.setStatus(status);
        noticeService.updateById(notice);
        return Result.success();
    }
    
    /**
     * 置顶/取消置顶公告
     */
    @PutMapping("/top/{id}")
    public Result<Void> toggleTop(
            @PathVariable Long id,
            @RequestParam(defaultValue = "1") Integer isTop) {
        Notice notice = new Notice();
        notice.setId(id);
        notice.setIsTop(isTop);
        noticeService.updateById(notice);
        return Result.success();
    }
    
    /**
     * 获取最新公告
     */
    @GetMapping("/latest")
    public Result<Notice> getLatestNotice() {
        Notice notice = noticeService.getLatestNotice();
        return Result.success(notice);
    }
} 